/*
 * ﻿Copyright (C) 2009-2013 NewMain Softech
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.newmainsoftech.gwetons.client.timer;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.logging.Level;

import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Window;
import com.newmainsoftech.gwetons.client.timer.TimeredCracker.TimerSingletonControllerAttacher;
import com.newmainsoftech.gwetons.shared.TargetEnvironment;
import com.newmainsoftech.gwetons.shared.logging.LoggerWrap;
import com.newmainsoftech.gwetons.shared.logging.LoggerWrapAdapterTemplate;
import com.newmainsoftech.gwetons.shared.timer.TimerController;
import com.newmainsoftech.gwetons.shared.timer.TimerEventListener;

/**
 * Default out-of-box client-side implementation of {@link TimerController} interface.
 * 
 * @author <a href="mailto:artymt@gmail.com">Arata Y.</a>
 */
public class TimerControllerImpl extends LoggerWrapAdapterTemplate implements TimerController {
	@Override
	protected String getNameForLogging() {
		return this.getClass().getName();
	}

	void hookWindowClosing() {
		// Catch the window closing event.
		Window.addCloseHandler(
			new CloseHandler<Window>() {
				public void onClose( CloseEvent<Window> event) {
					cancelAll();
				}
		});
	}
	
	protected TimerControllerImpl() {
		hookWindowClosing();
	}

	public TargetEnvironment getTargetEnvironment() {
		return TargetEnvironment.JavaScript;
	}

	private native int createInterval( TimeredCracker timeredCracker, int period) /*-{
		return $wnd.setInterval(
			function() { timeredCracker.@com.newmainsoftech.gwetons.client.timer.TimeredCracker::fire()(); },
			period
			);
	}-*/;

	private native int createTimeout( TimeredCracker timeredCracker, int delay) /*-{
		return $wnd.setTimeout(
			function() { timeredCracker.@com.newmainsoftech.gwetons.client.timer.TimeredCracker::fire()(); },
			delay);
	}-*/;
	
	private native void clearInterval( int id) /*-{
		$wnd.clearInterval( id);
	}-*/;
	
	private native void clearTimeout( int id) /*-{
		$wnd.clearTimeout( id);
	}-*/;
	
	class TimerUnitModel {
		private final int id;
			public int getId() {
				return id;
			}
		private final TimeredCracker timeredCracker;
			public TimeredCracker getTimeredCracker() {
				return timeredCracker;
			}

		public TimerUnitModel( int id, TimeredCracker timeredCracker) {
			this.id = id;
			this.timeredCracker= timeredCracker;
		}		
	}
		TimerUnitModel createTimerUnitModelObject( int id, TimeredCracker timeredCracker) {
			return new TimerUnitModel( id, timeredCracker);
		}
	
	LinkedHashMap<TimerEventListener, TimerUnitModel> timerEventListenerLinkedHashMap 
	= new LinkedHashMap<TimerEventListener, TimerUnitModel>();
		
	public void cancel( TimerEventListener timerEventListener) {
		String methodName = "cancel";
		LoggerWrap loggerWrap = getLoggerWrap();
		loggerWrap.entering( methodName, new Object[]{ timerEventListener});
		
		if ( timerEventListener == null) {
			loggerWrap.log( 
					Level.INFO, 
					"Simply returning because value fo timerEventListener argument is null."
					);
			loggerWrap.exiting( methodName);
			return;
		}
		
		TimerUnitModel timerUnitModel = timerEventListenerLinkedHashMap.get( timerEventListener);
			if ( timerUnitModel == null) {
				loggerWrap.log( 
						Level.FINE, 
						"Simply returning because could not find timerEventListener argument value " 
						+ "as having being scheduled for execution."
						);
				loggerWrap.exiting( methodName);
				return;
			}
		if ( timerUnitModel.getTimeredCracker().isForRepeat()) clearInterval( timerUnitModel.id);
		else clearTimeout( timerUnitModel.id);
		timerEventListenerLinkedHashMap.remove( timerEventListener);
		
		loggerWrap.log( 
				Level.FINE, 
				"Canceled timerEventListener(=" + timerEventListener.toString() 
				+ ") from futher execution." 
				);
		loggerWrap.exiting( methodName);
	}

	public void cancelAll() {
		String methodName = "cancelAll";
		LoggerWrap loggerWrap = getLoggerWrap();
		loggerWrap.entering( methodName, null);
		
		if ( timerEventListenerLinkedHashMap.isEmpty()) {
			loggerWrap.log( 
					Level.FINE, 
					"Simply returning because could not find any event being scheduled for execution."
					);
			loggerWrap.exiting( methodName);
			return;
		}

		TimerEventListener[] timerEventListenerArray = 
			timerEventListenerLinkedHashMap.keySet().toArray( new TimerEventListener[ 0]);
		for( 
				int timerEventListenerIndex = timerEventListenerLinkedHashMap.size() - 1;
				timerEventListenerIndex > -1;
				timerEventListenerIndex--
				) 
		{
			TimerEventListener timerEventListener = timerEventListenerArray[ timerEventListenerIndex];
			cancel( timerEventListener);
		} // for
		
		loggerWrap.log( 
				Level.FINE, 
				"Canceled " + timerEventListenerArray.length 
				+ " TimerEventListenerIntf event object(s) from futher execution." 
				);
		loggerWrap.exiting( methodName);
	}
	
	
	class TimerEventHandOver implements TimerSingletonControllerAttacher {
		private final TimerEventListener timerEventListener;
		private final boolean forRepeat;
		public TimerEventHandOver( TimerEventListener timerEventListener, boolean forRepeat) {
			this.timerEventListener = timerEventListener;
			this.forRepeat = forRepeat;
		}
		
		public void fire() {
			if ( timerEventListener != null) timerEventListener.fire();
		}
		public void remove() {
			if ( timerEventListener == null) return;
			if ( forRepeat) return;
			timerEventListenerLinkedHashMap.remove( timerEventListener);			
		}
	} 
		TimerEventHandOver createTimerEventHandOverObject( 
				TimerEventListener timerEventListener, boolean forRepeat) {
			
			return new TimerEventHandOver( timerEventListener, forRepeat);
		}
		
	
	public void schedule( 
			TimerEventListener timerEventListener, int delayMillis) {
		
		if ( timerEventListener == null) {
			throw new IllegalArgumentException( "timeredMethodHandler argument cannot be null.");
		}
		if ( delayMillis <= 0) {
			throw new IllegalArgumentException( "delayMillis argument must be bigger than 0");
		}
		
		String methodName = "schedule";
		LoggerWrap loggerWrap = getLoggerWrap();
		loggerWrap.entering( methodName, new Object[]{ timerEventListener, delayMillis});
		
		if ( !timerEventListenerLinkedHashMap.isEmpty()) {
			cancel( timerEventListener);
		}
		
		TimeredCracker timeredCracker = 
			new TimeredCracker( 
					false, 
					createTimerEventHandOverObject( timerEventListener, false)
					);
		int timerId = createTimeout( timeredCracker, delayMillis);
		timerEventListenerLinkedHashMap.put( 
				timerEventListener, 
				createTimerUnitModelObject( timerId, timeredCracker)
				);
		
		loggerWrap.log( 
				Level.FINE, 
				"Scheduled " + timerEventListener.toString() + " event being executed at about " 
				+ (new Date( (new Date()).getTime() + delayMillis)).toString() + "." 
				);
		loggerWrap.exiting( methodName);
	}

	public void scheduleRepeating( 
			TimerEventListener timerEventListener, int periodMillis) {
		
		if ( timerEventListener == null) {
			throw new IllegalArgumentException( "timeredMethodHandler argument cannot be null.");
		}
		if (periodMillis <= 0) {
			throw new IllegalArgumentException( "periodMillis argument must be bigger than 0");
		}
		
		String methodName = "scheduleRepeating";
		LoggerWrap loggerWrap = getLoggerWrap();
		loggerWrap.entering( methodName, new Object[]{ timerEventListener, periodMillis});
		
		if ( !timerEventListenerLinkedHashMap.isEmpty()) {
			cancel( timerEventListener);
		}
		
		TimeredCracker timeredCracker = 
			new TimeredCracker( 
					true, 
					createTimerEventHandOverObject( timerEventListener, true)
					);
		int timerId = createInterval( timeredCracker, periodMillis);
		timerEventListenerLinkedHashMap.put( 
				timerEventListener, 
				createTimerUnitModelObject( timerId, timeredCracker)
				);
		
		loggerWrap.log( 
				Level.FINE, 
				"Scheduled " + timerEventListener.toString() + " event being executed repeadetely " 
				+ "with " + periodMillis + "[msec] interval." 
				);
		loggerWrap.exiting( methodName);
	}
}